from PyQt5.QtCore import Qt          # PyQt6 改成 PyQt6.QtCore
from PyQt5.QtGui import QPalette, QColor
from PyQt5.QtWidgets import (QApplication, QMainWindow,
                             QPushButton, QVBoxLayout, QWidget)
import sys

# ---------- 主题调色板 ----------
class PaletteTheme:
    @staticmethod
    def light():
        p = QPalette()
        p.setColor(QPalette.Window,          QColor(240, 240, 240))
        p.setColor(QPalette.WindowText,      Qt.black)
        p.setColor(QPalette.Base,            Qt.white)
        p.setColor(QPalette.AlternateBase,   QColor(245, 245, 245))
        p.setColor(QPalette.Text,            Qt.black)
        p.setColor(QPalette.Button,           QColor(240, 240, 240))
        p.setColor(QPalette.ButtonText,      Qt.black)
        p.setColor(QPalette.Highlight,       QColor(0, 120, 215))
        p.setColor(QPalette.HighlightedText, Qt.white)
        return p

    @staticmethod
    def dark():
        p = QPalette()
        p.setColor(QPalette.Window,          QColor(53, 53, 53))
        p.setColor(QPalette.WindowText,      Qt.white)
        p.setColor(QPalette.Base,            QColor(25, 25, 25))
        p.setColor(QPalette.AlternateBase,   QColor(53, 53, 53))
        p.setColor(QPalette.Text,            Qt.white)
        p.setColor(QPalette.Button,          QColor(53, 53, 53))
        p.setColor(QPalette.ButtonText,      Qt.white)
        p.setColor(QPalette.Highlight,       QColor(42, 130, 218))
        p.setColor(QPalette.HighlightedText, Qt.white)
        return p

    @staticmethod
    def apply(palette):
        app = QApplication.instance()
        app.setPalette(palette)
        # 强制所有已有控件重绘
        for w in app.allWidgets():
            w.setPalette(palette)

# ---------- 主窗口 ----------
class Win(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('无 QSS 主题切换（修正版）')
        central = QWidget()
        lay = QVBoxLayout(central)

        # 用「立即绑定」函数避免 lambda 迟绑定
        def make_switcher(pal, name):
            btn = QPushButton(f'切换到 {name}')
            # 关键点：把 pal 直接绑进 lambda 默认参数
            btn.clicked.connect(lambda _checked, p=pal: PaletteTheme.apply(p))
            return btn

        lay.addWidget(make_switcher(PaletteTheme.light(), 'Light'))
        lay.addWidget(make_switcher(PaletteTheme.dark(),  'Dark'))
        self.setCentralWidget(central)

# ---------- 启动 ----------
if __name__ == '__main__':
    app = QApplication(sys.argv)
    PaletteTheme.apply(PaletteTheme.light())
    w = Win()
    w.show()
    sys.exit(app.exec())      # PyQt5/6 通用；旧 exec_() 已弃用